/**
 * Copyright (c) 2014-now, secondriver (secondriver@yeah.net).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package secondriver.jfinal.rack.kit;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jfinal.kit.StrKit;

/**
 * StrKit.
 */
public class RockStrKit {

	/**
	 * 字符串数组有null,""元素时返回true
	 * 
	 * @param strings
	 * @return
	 */
	public static boolean isBlank(String... strings) {
		if (null == strings) {
			return true;
		}
		for (String str : strings) {
			if (isBlank(str)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 生成指定字符串MD5摘要
	 * 
	 * @param str
	 *            要处理的字符串
	 * @return 如果发生异常返回null,否则返回摘要信息字符串
	 */
	public static String simpleMD5(String str) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException ex) {
			ex.printStackTrace();
			return "";
		}
		byte[] resultByte = messageDigest.digest(str.getBytes());
		StringBuffer result = new StringBuffer();
		for (int i = 0; i < resultByte.length; i++) {
			result.append(Integer.toHexString(0xFF & resultByte[i]));
		}
		return result.toString();
	}

	/**
	 * 生成一个简单的当前时间的时间戳
	 * 
	 * @return 返回格式为：yyMMddHHmmss的当前时间的时间戳
	 */
	public static String simpleTimeStamp() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
		return sdf.format(new Date());
	}

	/**
	 * 字符串数组以指定分隔符连成字符串
	 * 
	 * @param array
	 *            字符串数组
	 * @param split
	 *            链接分隔符
	 * @return 连接后的字符串，如果null==array返回""
	 */
	public static String covertStringArrayToString(String[] array, String split) {
		if (array == null) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		for (int i = 0, length = array.length; i < length; i++) {
			if (i != length - 1) {
				sb.append(array[i].toString()).append(split);
			} else {
				sb.append(array[i].toString());
			}
		}
		return sb.toString();
	}

	/**
	 * 转化指定数字为中文数字
	 * 
	 * @param number
	 *            数字为0-9
	 * @return 中文数字
	 */
	public static String covertChineseNumber(int number) {
		if (number > 10 || number < 0) {
			throw new IllegalArgumentException("Please number must be 0 - 9.");
		}
		String[] chineseNum = { "零", "一", "二", "三", "四", "五", "六", "七", "八",
				"九" };
		return chineseNum[number];
	}

	/**
	 * 转化指定的文件尺寸为带单位的描述
	 * 
	 * @param fileSize
	 *            指定文件尺寸默认不带单位，即B为最小 单位，如：1024B
	 * @return 返回带单位的描述，如：1024B转化为1.00MB
	 */
	public static String covertFileSizeDescription(String fileSize) {
		String result = "";
		DecimalFormat df = new DecimalFormat("0.00");
		double dbFileSize = Double.parseDouble(fileSize);
		if (dbFileSize >= 1024.0D) {
			if (dbFileSize >= 1048576.0D) {
				if (dbFileSize >= 1073741824.0D) {
					result = df
							.format(dbFileSize / 1024.0D / 1024.0D / 1024.0D)
							+ "GB";
				} else {
					result = df.format(dbFileSize / 1024.0D / 1024.0D) + "MB";
				}
			} else {
				result = df.format(dbFileSize / 1024.0D) + "KB";
			}
		} else {
			result = df.format(dbFileSize / 1024.0D) + "KB";
		}
		return result;
	}

	/**
	 * 清除指定元素中的HTML元素
	 * 
	 * @param element
	 *            指定元素
	 * @return 返回不含有HTML元素的文本
	 */
	public static String getTxtWithoutHTMLElement(String element) {
		if ((element == null) || ("".equals(element.trim()))) {
			return element;
		}
		Pattern pattern = Pattern.compile("<[^<|^>]*>");
		Matcher matcher = pattern.matcher(element);
		StringBuffer txt = new StringBuffer();
		while (matcher.find()) {
			String group = matcher.group();
			if (group.matches("<[\\s]*>"))
				matcher.appendReplacement(txt, group);
			else {
				matcher.appendReplacement(txt, "");
			}
		}
		matcher.appendTail(txt);
		String result = txt.toString().replaceAll("\n", "");
		result = result.replaceAll(" ", "");
		return result;
	}

	/**
	 * 获取指定长度的随机数字字符串
	 * 
	 * @param length
	 *            长度
	 * @return 指定长度的随着数字字符串
	 */
	public static String getRadmonNumberString(int length) {
		Random random = new Random();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < length; i++) {
			sb.append(String.valueOf(random.nextInt(10)));
		}
		return sb.toString();
	}

	/**
	 * 字符串转化为UTF-8编码
	 * 
	 * @param str
	 *            指定字符串
	 * @return 返回编码结果,如果str==null或者str==""将返回""
	 */
	public static String toUTF8(String str) {
		if (null == str || "".equals(str)) {
			return "";
		} else {
			try {
				return new String(str.getBytes("ISO8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return "";
	}

	/**
	 * 字符串转化为指定编码
	 * 
	 * @param str
	 *            指定字符串
	 * @param charset
	 *            字符串编码
	 * @return 返回编码结果,如果str==null或者str==""将返回""
	 */
	public static String toCharset(String str, String charset) {
		if (null == str || "".equals(str))
			return "";
		try {
			return new String(str.getBytes("ISO8859-1"), charset);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "";
	}

	/**
	 * 截取指定长度的字符串并添加省略符
	 * 
	 * @param content
	 * @param length
	 * @return
	 */
	public static String getLimitLengthString(String content, int length) {
		return getLimitLengthString(content, length, "...");
	}

	/**
	 * 截取指定长度的字符串并添加指定的省略符
	 * 
	 * @param content
	 * @param length
	 * @param subfix
	 * @return
	 */
	public static String getLimitLengthString(String content, int length,
			String subfix) {
		if (content == null)
			return "";
		if (content.length() > length) {
			content = content.substring(0, length)
					+ (StrKit.isBlank(subfix) ? "" : subfix);
		}
		return content;
	}

	/**
	 * This method takes a string which may contain HTML tags (ie, &lt;b&gt;,
	 * &lt;table&gt;, etc) and converts the '&lt'' and '&gt;' characters to
	 * their HTML escape sequences.
	 * 
	 * @param input
	 *            the text to be converted.
	 * @return the input string with the characters '&lt;' and '&gt;' replaced
	 *         with their HTML escape sequences.
	 */
	public static String escapeHTMLTags(String input) {
		if (input == null || input.length() == 0) {
			return input;
		}
		StringBuffer buf = new StringBuffer(input.length());
		char ch = ' ';
		for (int i = 0; i < input.length(); i++) {
			ch = input.charAt(i);
			switch (ch) {
			case '<':
				buf.append("&lt;");
				break;
			case '>':
				buf.append("&gt;");
				break;
			case '&':
				buf.append("&amp;");
				break;
			case '"':
				buf.append("&quot;");
				break;
			default:
				buf.append(ch);
				break;
			}
		}
		return buf.toString();
	}

	/**
	 * Text convert HTML
	 * 
	 * @param content
	 * @return
	 */
	public static String textToHtml(String content) {
		if (StrKit.isBlank(content)) {
			return "";
		} else {
			StringBuilder sb = new StringBuilder();
			char c = ' ';
			for (int i = 0, l = content.length(); i < l; i++) {
				c = content.charAt(i);
				if (c == '\n') {
					sb.append("<br />");
				} else {
					sb.append(c);
				}
			}
			return sb.toString();
		}
	}
}